package com.dream.base.web.filter;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.jstl.core.Config;

import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.util.WebUtils;
/**
 * 
 * @author Evan
 * @date 2013-8-25
 * 
 */
public class I18nFilter implements Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		
		if(!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)){
			throw new ServletException("the bad http request or response!");
		}
		
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		Locale locale = (Locale) WebUtils.getSessionAttribute(httpRequest, SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME);
		
		if(locale == null){
			locale = httpRequest.getLocale();
			WebUtils.setSessionAttribute(httpRequest, SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);
		}
		Config.set(httpRequest.getSession(true),Config.FMT_LOCALE, locale);
		response.setLocale(locale);
		filterChain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
